package com.css.fxfzxczh.modules.synthesizeInfoManage.knowledgeManagement.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.css.fxfzxczh.base.attachment.entity.AttachmentInfoEntity;
import com.css.fxfzxczh.base.attachment.service.AttachmentInfoService;
import com.css.fxfzxczh.base.dict.service.DictService;
import com.css.fxfzxczh.base.response.RestResponse;
import com.css.fxfzxczh.constants.YNEnum;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.entity.EarEveManage;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.service.EarEveManageService;
import com.css.fxfzxczh.modules.synthesizeInfoManage.knowledgeManagement.entity.KnowledgeManagement;
import com.css.fxfzxczh.modules.synthesizeInfoManage.knowledgeManagement.repository.KnowledgeManagementRepository;
import com.css.fxfzxczh.modules.synthesizeInfoManage.knowledgeManagement.service.KnowledgeManagementService;
import com.css.fxfzxczh.modules.synthesizeInfoManage.knowledgeManagement.verify.KnoBaseVerify;
import com.css.fxfzxczh.modules.synthesizeInfoManage.knowledgeManagement.vo.KnoBaseExcelVo;
import com.css.fxfzxczh.modules.synthesizeInfoManage.knowledgeManagement.vo.KnowledgeManagementVO;
import com.css.fxfzxczh.modules.synthesizeInfoManage.personnelManagement.entity.PersonnelManagement;
import com.css.fxfzxczh.modules.synthesizeInfoManage.personnelManagement.vo.ImportExcelVo;
import com.css.fxfzxczh.util.*;
import com.css.fxfzxczh.web.PlatformSessionContext;
import com.css.fxfzxczh.zcpt.sys.entity.SUser;
import com.css.fxfzxczh.zcpt.sys.service.SUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.*;

/**
 * @Author: zhangSongRui
 * @CreateTime: 2023/01/11
 * @Description: 知识库管理
 */
@Service
public class KnowledgeManagementServiceImpl implements KnowledgeManagementService {

    @Resource
    private KnowledgeManagementRepository knowledgeManagementRepository;
    @Resource
    private AttachmentInfoService attachmentInfoService; // 附件
    @Resource
    SUserService sUserService;
    @Resource
    DictService dictService;
    @Autowired
    EarEveManageService earEveManageService;

    @Resource
    KnoBaseVerify knoBaseVerify;

    @Value("${image.localDir}")
    private String localDir;

    @Override
    public void save(KnowledgeManagement param) {
        EarEveManage currentEvent = earEveManageService.getCurrentEvent();
        param.setXsemId(currentEvent.getXsemId());
        param.setXkmId(UUID.randomUUID().toString().replaceAll("-", ""));
        param.setDelFlag(YNEnum.N.toString());
        String userID = PlatformSessionContext.getUserID(); // 获取当前登录用户
        param.setCreateUser(userID);
        param.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        knowledgeManagementRepository.save(param);
    }

    @Override
    public void updateById(KnowledgeManagement param) {
        String userID = PlatformSessionContext.getUserID(); // 获取当前登录用户
        param.setUpdateUser(userID);
        param.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        String zsk = dictService.getValueByDictCodeAndKey("zsk", param.getCategory());
        if (zsk.equals("基础知识库")){
            param.setXsemId("1");
        }
        knowledgeManagementRepository.updateById(param);
    }

    @Override
    public void deleteById(String id) {
        knowledgeManagementRepository.deleteById(id);
    }

    @Override
    public Map<String, Object> getPage(KnowledgeManagement queParams, int curPage, int pageSize) {
        Map<String, Object> page = knowledgeManagementRepository.getPage(queParams, curPage, pageSize);
        return page;
    }

    /**
     * 附件上传
     *
     * @param id       id
     * @param fileId   文件id
     * @param fileType 文件类型
     */
    @Override
    public void updateFile(String id, String fileId, String fileType ,String attachmentName) {
        KnowledgeManagement knowledgeManagement = new KnowledgeManagement();
        knowledgeManagement.setXkmId(id);
        knowledgeManagement.setAttachment(fileId);
        knowledgeManagement.setFileType(fileType);
        knowledgeManagement.setAttachmentName(attachmentName);
        knowledgeManagement.setUpdateUser(PlatformSessionContext.getUserID());
        knowledgeManagement.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        knowledgeManagementRepository.updateFile(knowledgeManagement);
    }

    /**
     * 解析excel并批量入库
     *
     * @param fileId
     * @param xsemId
     */
    @Override
    public void parseExcel(String fileId, String xsemId) {
        //根据id和文件名获取真实的放在磁盘上的文件
        AttachmentInfoEntity attachmentInfoEntity = attachmentInfoService.getAttach(fileId);
        String attachPath = attachmentInfoEntity.getAttachPath();
        //拼接真实路径
        String name = localDir + File.separator + attachPath;
        File file = new File(name);
        List<List<String>> date = new ArrayList<>();
        try {
            FileInputStream fis = new FileInputStream(file);
            //获取excel表格数据
            date = ExcelReaderUtil.readExcel(fis);
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<KnowledgeManagement> list = getList(date, xsemId);
        knowledgeManagementRepository.batchSave(list);
    }

    //解析数据
    private List<KnowledgeManagement> getList(List<List<String>> date, String xsemId) {
        ArrayList<KnowledgeManagement> personnelManagements = new ArrayList<>();
        String userID = PlatformSessionContext.getUserID();
        EarEveManage earEveManage = earEveManageService.findById(xsemId);
        for (int i = 1; i < date.size(); i++) {
            List<String> list = date.get(i);
            KnowledgeManagement obj = new KnowledgeManagement();
            //判断知识库类别
            if (list.get(1).equals("基础知识库")) {
                //基础知识库编号
                obj.setKnowledgeCode(getCode(""));
            } else {
                //地震事件编号
                obj.setXsemId(xsemId);
                //信息知识库编号
                obj.setKnowledgeCode(getCode(earEveManage.getEventCode()));
            }
            //id
            obj.setXkmId(UUID.randomUUID().toString().replaceAll("-", ""));
            obj.setDelFlag(YNEnum.N.toString());
            obj.setCreateUser(userID);
            obj.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            //名称
            obj.setKnowledgeName(list.get(0));
            //知识库类型 基础知识库,信息知识库
            obj.setCategory(dictService.getValueByDictCodeAndKey("zsk", list.get(1)));
            //描述信息
            obj.setCommentInfo(list.get(2));
            personnelManagements.add(obj);
        }
        return personnelManagements;
    }

    //知识库编号传入地震编号生成信息库编号,不传则生成基础库编号
    public KnowledgeManagement getKnowledgeCode(String xsemId) {
        KnowledgeManagement knowledgeManagement = new KnowledgeManagement();
        String user = sUserService.getSUser(PlatformSessionContext.getUserID());
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        knowledgeManagement.setCreateUser(sUser.getUserName());
        knowledgeManagement.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        knowledgeManagement.setCompany(sUser.getOrgName());
        /*String code;
        String PersonCode;
        if (xsemId == null) {
            code = knowledgeManagementRepository.getCode(null);
            PersonCode = "WZ";
            if (StringUtils.isBlank(code)) {
                PersonCode = PersonCode + "001";
            } else {
                String[] ries = code.split("WZ");
                String next = getNext(ries[1]);
                PersonCode = PersonCode + next;
            }
        } else {
            code = knowledgeManagementRepository.getCode(xsemId);
            String XsemCode =knowledgeManagementRepository.getXsemCode(xsemId);
            PersonCode = XsemCode + "WZ";
            if (StringUtils.isBlank(code)) {
                PersonCode = PersonCode + "001";
            } else {
                String[] ries = code.split("WZ");
                String next = getNext(ries[1]);
                PersonCode = PersonCode + next;
            }
        }
        //知识库编号
        knowledgeManagement.setKnowledgeCode(PersonCode);*/
        //文件类型
        knowledgeManagement.setFileType("png,jpg,jpeg");
        return knowledgeManagement;
    }

    @Override
    public void exportData(HttpServletResponse response, KnowledgeManagement param) {
        List<KnowledgeManagement> list = knowledgeManagementRepository.queryByParam(param);
        EasyPoiExcelUtil.exportExcel(list, "知识库列表", "sheet1", KnowledgeManagement.class, "知识库列表", response);
    }

    @Override
    public KnowledgeManagementVO findById(String id) {
        KnowledgeManagement know = knowledgeManagementRepository.findById(id);
        //根据id和文件名获取真实的放在磁盘上的文件
        AttachmentInfoEntity attachmentInfoEntity = attachmentInfoService.getAttach(know.getAttachment());
        KnowledgeManagementVO knowVO = new KnowledgeManagementVO();
        BeanUtils.copyProperties(know, knowVO);
        knowVO.setAttachmentInfoEntity(attachmentInfoEntity);
        String user = sUserService.getSUser(know.getCreateUser());
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        knowVO.setCreateUser(sUser.getUserName());
        return knowVO;
    }

    @Override
    public RestResponse importExcel(MultipartFile file, String xsemId) throws Exception {
// 导入的参数信息
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setImportFields(new String[]{"名称","知识库类别","描述信息"});
        params.setNeedVerify(true);
        params.setVerifyHandler(knoBaseVerify);//校验
        InputStream inputStream = null;

        inputStream = file.getInputStream();
        ExcelImportResult<KnoBaseExcelVo> result = ExcelImportUtil.importExcelMore(inputStream, KnoBaseExcelVo.class, params);
        List<KnoBaseExcelVo> failList = result.getFailList();
        if (PlatformObjectUtils.isNotEmpty(failList)) {
            StringBuilder errorMsg = new StringBuilder("<font size='5px' color='red'>导入失败：</font>");
            for (KnoBaseExcelVo importExcelVo : failList) {
                errorMsg.append("<font size='4px' ><br>").append("第").append(importExcelVo.getRowNum() + 1).append("行： ").append(importExcelVo.getErrorMsg()).append("</font>");
            }
            throw new RuntimeException(errorMsg.toString());
        }
        List<KnoBaseExcelVo> list = result.getList();
        if(list.isEmpty()){
            return RestResponse.fail("导入失败，模板数据为空!");
        }
        for(KnoBaseExcelVo item:list){
            String user = sUserService.getSUser(PlatformSessionContext.getUserID());
            SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
            KnowledgeManagement knowledgeManagement=new KnowledgeManagement();
            BeanUtils.copyProperties(item, knowledgeManagement);
            knowledgeManagement.setXsemId(xsemId);
            knowledgeManagement.setXkmId(UUIDGenerator.getUUID());
            knowledgeManagement.setDelFlag(YNEnum.N.toString());
            knowledgeManagement.setCreateUser(PlatformSessionContext.getUserID());
            knowledgeManagement.setCreateTime(new Date());
            if("1".equals(item.getCategory())){
                knowledgeManagement.setKnowledgeCode(getCode(""));
            }else{
                EarEveManage earEveManage = earEveManageService.findById(xsemId);
                knowledgeManagement.setKnowledgeCode(earEveManage.getEventCode());
            }

            knowledgeManagement.setCompany(sUser.getOrgName());
            knowledgeManagementRepository.save(knowledgeManagement);
        }
        return RestResponse.succeed("导入成功!");
    }

    @Override
    public String getCode(String eventCode) {
        EarEveManage currentEvent = earEveManageService.getCurrentEvent();
        eventCode=currentEvent.getEventCode();
        StringBuilder samPoiCode = new StringBuilder(eventCode);
        if(PlatformObjectUtils.isEmpty(eventCode)){
            samPoiCode.append("JCZSK");
        }else{
            samPoiCode.append("XXZSK");
        }
        DecimalFormat decimalFormat=new DecimalFormat("000");
        String num="";

        String maxNum=knowledgeManagementRepository.getMaxNum(samPoiCode.toString());
        if(PlatformObjectUtils.isEmpty(maxNum)){
            int i = 1;
            num=decimalFormat.format(i);
        }else{
            String substring="";
            if(PlatformObjectUtils.isEmpty(eventCode)){
                 substring = maxNum.substring(5);
            }else{
                 substring = maxNum.substring(19);
            }

            num = decimalFormat.format(Integer.parseInt(substring) + 1);
        }
        return samPoiCode.append(num).toString();
    }


    /****
     * 从哪里开始计数 比如startValue=2，则会从003,004,005等
     * @param startValue
     * @return
     */
    public String getNext(String startValue) {
        Integer i = Integer.valueOf(startValue);
        String format = String.format("%03d", i + 1);
        return format;
    }
}
